var http = require('http'),
	url = require('url');

var items = [];

var server = http.createServer(function(req, res) {

	// Test 1

	// var url = 'http://baidu.com';
	// var body = '<p>Redirecting to <a href="' + url + '">'
	// 			+ url + '</a></p>';
	// res.setHeader('Location', url);
	// res.setHeader('Content-Length', body.length);
	// res.setHeader('Content-Type', 'text/html');
	// res.statusCode = 302;
	// res.end(body);

	// Test 2

	switch (req.method) {
		case 'POST':
			var item = '';
			req.setEncoding('utf8');
			req.on('data', function(chunk) {
				item += chunk;
			});
			req.on('end', function() {
				items.push(item);
				res.end('OK\n');
			});
			break;
		case 'GET':
			// items.forEach(function(item, i) {
			// 	res.write(i + ') ' + item + '\n');
			// });
			var body = items.map(function(item, i) {
				return i + ') ' + item;
			}).join('\n');
			res.setHeader('Content-Length', Buffer.byteLength(body));
			res.setHeader('Content-Type', 'text/palin; charset="utf-8"');
			res.end(body);
			break;
		case 'PUT':
			var item = '';
			req.setEncoding('utf-8');
			req.on('data', function(chunk) {
				tiem += chunk;
			});
			req.on('end', function() {
				var path = url.parse(req.url).pathname;
				var i = parseInt(path.slice(1));
				if (isNaN(i)) {
					res.statusCode = 400;
					res.end('Invalid item id');
				} else if (!items[i]) {
					res.statusCode = 404;
					res.end('Item not found');
				} else {
					items[i] = item;
					res.end('OK\n');
				}

			});
		case 'DELETE':
			var path = url.parse(req.url).pathname;
			var i = parseInt(path.slice(1), 10);
			if (isNaN(i)) {
				res.statusCode = 400;
				res.end('Invalid item id');
			} else if (!items[i]) {
				res.statusCode = 404;
				res.end('Item not found');
			} else {
				items.splice(i, 1);
				res.end('OK\n');
			}
			break;
	}

});

server.listen(8000);